package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/user/passport")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    //@Validated 验证 UserInfo 里面的值 在UserInfo 的成员变量打注解（@NotNull等）
    public Result login(@Validated @RequestBody UserInfo userInfo){
        //校验用户名密码是否正确
        userInfo = userInfoService.checkInfo(userInfo);

        if (null !=userInfo){
            //验证成功
            String uuid = UUID.randomUUID().toString();
            Map map = new HashMap<>();
            map.put("nickName",userInfo.getNickName());
            map.put("token",uuid);

            //添加到redis中
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+uuid,userInfo.getId().toString());
            //过期时间就不设置了
            return Result.ok(map);
        }
        return Result.fail().message("用户名或密码是不正确的");
    }

    //查询当前用户的所有收货地址集合
    @GetMapping("/getUserAddress")
    public List<UserAddress> getUserAddress(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> userAddress = userInfoService.getUserAddress(userId);
        System.out.println("userAddress = " + userAddress);
        return userAddress;
    }

//    @GetMapping("/logout")
//    public Result logout(HttpServletRequest request){
//        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));
//        System.out.println("token = " +RedisConst.USER_LOGIN_KEY_PREFIX+ request.getHeader("token"));
//        return Result.ok();
//    }
}
